// Created by Roman Novitsky on 04.06.2009


#region Imported Namespaces


using System;
using System.Drawing;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;

using WtfManager.Framework;


#endregion


namespace WtfManager.Utilities
{
  [ValueConversion(typeof(IntPtr), typeof(ImageSource))]
  public class IconHandleToImageSourceConverter: Service, IValueConverter
  {
    #region Fields


    private static IconHandleToImageSourceConverter _instance;


    #endregion


    #region Constructors/Finalizers


    internal IconHandleToImageSourceConverter()
    {
    }


    #endregion


    #region Properties/Indexers


    public override string Description
    {
      get
      {
        return "Converts icon handle to ImageSource";
      }
    }

    public static IconHandleToImageSourceConverter Instance
    {
      get
      {
        return _instance;
      }
    }

    public override string Name
    {
      get
      {
        return "Icon Handle to Image Source Converter";
      }
    }


    #endregion


    #region Methods


    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
      if (!(value is IntPtr))
      {
        return null;
      }

      var handle = (IntPtr)value;

      try
      {
        Bitmap bitmap = Image.FromHbitmap(handle);

        return bitmap.ToImageSource();
      }
      catch
      {
        try
        {
          Bitmap bitmap = Bitmap.FromHicon(handle);

          return bitmap.ToImageSource();
        }
        catch
        {
          return null;
        }
      }
    }


    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
      throw new NotSupportedException();
    }


    protected override void OnStateChnaged()
    {
      _instance = State == FrameworkComponentState.Initialized ? this : null;
    }


    protected override void OnUnload()
    {
    }


    protected override FrameworkComponentState OnInitialize()
    {
      return FrameworkComponentState.Initialized;
    }


    protected override FrameworkComponentState OnLoad()
    {
      return FrameworkComponentState.Loaded;
    }


    #endregion
  }
}